package services

import (
	"fmt"
	"gitee.com/zhoulvvv/my_go_gateway/dao"
	"gitee.com/zhoulvvv/my_go_gateway/dto"
	"gitee.com/zhoulvvv/my_go_gateway/public"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"log"
	"strings"
	"time"
)

type ServiceServices struct {
	tx *gorm.DB
}

func NewServiceServices() (*ServiceServices, error) {
	tx, err := lib.GetGormPool("default")
	if err != nil {
		return nil, errors.New("获取数据库连接池失败")
	}
	return &ServiceServices{
		tx: tx,
	}, nil
}

// 服务列表
func (ss *ServiceServices) GetPageList(c *gin.Context, param *dto.ServiceListInput) (*dto.ServiceListOutput, error) {
	// 计算分页偏移量
	offset := (param.PageNo - 1) * param.PageSize
	param.PageNo = offset
	serviceInfo := &dao.ServiceInfo{}
	// 分页读取服务基本信息
	serviceInfoList, total, err := serviceInfo.PageList(c, ss.tx, param)
	if err != nil {
		return nil, errors.New("分页查询服务列表出现错误")
	}

	itemList := []dto.ServiceListItemOutput{}
	serviceDetailServices, err := NewServiceDetailServices()
	if err != nil {
		return nil, errors.New("ServiceDetailServices 创建失败：" + err.Error())
	}
	serviceLoadBalanceServices, err := NewServiceLoadBalanceServices()
	if err != nil {
		return nil, errors.New("NewServiceLoadBalanceServices 创建失败：" + err.Error())
	}
	for _, serviceInfo := range serviceInfoList {
		// 获取服务的具体信息
		serviceDetailModel, err := serviceDetailServices.GetServiceDetail(c, &serviceInfo)
		if err != nil {
			return nil, errors.New("获取serviceDetail信息失败：" + err.Error())
		}
		// 组装服务的地址
		// 1。http路径接入 clusterIp+clusterPort+path
		// 2。http域名接入 domain
		// 3。tcp、grpc接入 clusterIp+servicePort
		serviceAddr := "unknow"
		clusterIp := lib.GetStringConf("base.cluster.cluster_ip")
		clusterPort := lib.GetStringConf("base.cluster.cluster_port")
		clusterSSLPort := lib.GetStringConf("base.cluster.cluster_ssl_port")
		if serviceDetailModel.Info.LoadType == public.LoadTypeHTTP {
			if serviceDetailModel.HTTPRule.RuleType == public.HTTPRuleTypeDomain {
				serviceAddr = serviceDetailModel.HTTPRule.Rule
			} else if serviceDetailModel.HTTPRule.RuleType == public.HTTPRuleTypePrefix &&
				serviceDetailModel.HTTPRule.NeedHttps == 1 {
				serviceAddr = fmt.Sprintf("%s:%s%s", clusterIp, clusterSSLPort, serviceDetailModel.HTTPRule.Rule)
			} else if serviceDetailModel.HTTPRule.RuleType == public.HTTPRuleTypePrefix &&
				serviceDetailModel.HTTPRule.NeedHttps == 0 {
				serviceAddr = fmt.Sprintf("%s:%s%s", clusterIp, clusterPort, serviceDetailModel.HTTPRule.Rule)
			}
		} else if serviceDetailModel.Info.LoadType == public.LoadTypeTCP {
			serviceAddr = fmt.Sprintf("%s:%d", clusterIp, serviceDetailModel.TCPRule.Port)
		} else if serviceDetailModel.Info.LoadType == public.LoadTypeGRPC {
			serviceAddr = fmt.Sprintf("%s:%d", clusterIp, serviceDetailModel.GRPCRule.Port)
		}
		serviceCounter, err := public.FlowCounterHandler.GetCounter(public.FlowServicePrefix + serviceInfo.ServiceName)
		if err != nil {
			return nil, errors.New("获取QPS计数器失败：" + err.Error())
		}
		// 获取服务的IP列表
		ipList := serviceLoadBalanceServices.GetIPListByModel(c, serviceDetailModel.LoadBalance)
		item := dto.ServiceListItemOutput{
			ID:          int64(serviceInfo.Id),
			ServiceName: serviceInfo.ServiceName,
			ServiceDesc: serviceInfo.ServiceDesc,
			LoadType:    serviceInfo.LoadType,
			ServiceAddr: serviceAddr,
			Qps:         serviceCounter.QPS,
			Qpd:         serviceCounter.TotalCount,
			TotalNode:   len(ipList),
		}
		itemList = append(itemList, item)
	}
	out := &dto.ServiceListOutput{
		Total: int(total),
		List:  itemList,
	}
	return out, nil
}

func (ss *ServiceServices) Find(c *gin.Context, param *dao.ServiceInfo) (*dao.ServiceInfo, error) {
	return param.Find(c, ss.tx, param)
}

// 删除服务
func (ss *ServiceServices) DeleteServiceInfo(c *gin.Context, param *dto.ServiceDeleteInput) error {
	// 查询服务信息
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{Id: param.ID})
	if err != nil {
		return errors.New("删除服务时查询服务失败：" + err.Error())
	}
	// 设置服务为删除
	serviceInfo.IsDelete = 1
	serviceInfo.Save(c, ss.tx)
	return nil
}

// 服务详情
func (ss *ServiceServices) GetServiceDetail(c *gin.Context, param *dto.ServiceDetailInput) (*dao.ServiceDetail, error) {
	// 查询服务信息
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{Id: param.ID})
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.New("查询服务基本信息失败：" + err.Error())
	}
	if serviceInfo == nil {
		return nil, errors.New("服务不存在：" + err.Error())
	}
	// 获取服务关联的数据
	serviceDetailServicesModel, err := NewServiceDetailServices()
	if err != nil {
		return nil, err
	}
	serviceDetail, err := serviceDetailServicesModel.GetServiceDetail(c, serviceInfo)
	if err != nil {
		return nil, errors.New("查询服务关联信息失败：" + err.Error())
	}
	return serviceDetail, nil
}

// 服务流量统计
func (ss *ServiceServices) GetServiceStat(c *gin.Context, param *dto.ServiceStatInput) (*dto.ServiceStatOutput, error) {
	// 查询服务信息
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{Id: param.ID})
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errors.New("查询服务基本信息失败：" + err.Error())
	}
	if serviceInfo == nil {
		return nil, errors.New("服务不存在：" + err.Error())
	}
	// 获取服务关联的数据
	serviceDetailServicesModel, err := NewServiceDetailServices()
	if err != nil {
		return nil, err
	}
	_, err = serviceDetailServicesModel.GetServiceDetail(c, serviceInfo)
	if err != nil {
		return nil, errors.New("查询服务关联信息失败：" + err.Error())
	}
	// 拿取当天的流量统计
	counter, err := public.FlowCounterHandler.GetCounter(public.FlowServicePrefix + serviceInfo.ServiceName)
	if err != nil {
		return nil, errors.New("获取服务QPS计数器失败：" + err.Error())
	}
	todayList := []int64{}
	currentTime := time.Now()
	// time.Now().Hour() 获取当前小时
	for i := 0; i <= currentTime.Hour(); i++ {
		newTime := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), i, 0, 0, 0, lib.TimeLocation)
		// 获取当前小时的QPS
		hourData, err := counter.GetHourData(newTime)
		if err != nil {
			log.Printf("获取 %s 服务当天 %s 小时的QPS数据出现错误：%s\n", serviceInfo.ServiceName, newTime.Format("2006010215"), err.Error())
		}
		todayList = append(todayList, hourData)
	}

	// 拿取昨天的流量统计
	yesterdayList := []int64{}
	// 获取昨天的时间
	yesterTime := currentTime.Add(-1 * time.Duration(time.Hour*24))
	for i := 0; i <= 23; i++ {
		newTime := time.Date(yesterTime.Year(), yesterTime.Month(), yesterTime.Day(), i, 0, 0, 0, lib.TimeLocation)
		// 获取当前小时的QPS
		yesterData, err := counter.GetHourData(newTime)
		if err != nil {
			log.Printf("获取 %s 服务昨天 %s 小时的QPS数据出现错误：%s\n", serviceInfo.ServiceName, newTime.Format("2006010215"), err.Error())
		}
		yesterdayList = append(yesterdayList, yesterData)
	}

	return &dto.ServiceStatOutput{
		Today:     todayList,
		Yesterday: yesterdayList,
	}, nil
}

// HTTP 服务添加
func (ss *ServiceServices) AddServiceInfoHTTP(c *gin.Context, param *dto.ServiceAddHTTPInput) error {
	// 校验服务名称是否存在
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{ServiceName: param.ServiceName, IsDelete: 0})
	if err == nil {
		return errors.New(serviceInfo.ServiceName + "服务名称已经存在")
	}
	// 校验接入类型地址是否存在
	httpRule := &dao.HttpRule{RuleType: param.RuleType, Rule: param.Rule}
	if _, err = httpRule.Find(c, ss.tx, httpRule); err == nil {
		return errors.New("接入类型前缀或者域名已经存在")
	}
	// 校验IP列表和权重列表是否相等
	if len(strings.Split(param.IpList, "\n")) !=
		len(strings.Split(param.WeightList, "\n")) {
		return errors.New("IP列表和权重列表不一致")
	}
	// 开启事务
	ss.tx = ss.tx.Begin()
	// 添加服务基本信息
	serviceInfoModel := &dao.ServiceInfo{
		LoadType:    public.LoadTypeHTTP,
		ServiceName: param.ServiceName,
		ServiceDesc: param.ServiceDesc,
		IsDelete:    0,
	}
	if err := serviceInfoModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务基本信息报错：" + err.Error())
	}
	// 添加HTTP规则信息
	httpRuleMode := &dao.HttpRule{
		ServiceId:      serviceInfoModel.Id,
		RuleType:       param.RuleType,
		Rule:           param.Rule,
		NeedHttps:      param.NeedHttps,
		NeedWebsocket:  param.NeedWebsocket,
		NeedStripUri:   param.NeedStripUri,
		UrlRewrite:     param.UrlRewrite,
		HeaderTransfor: param.HeaderTransfor,
	}
	if err := httpRuleMode.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务规则信息报错：" + err.Error())
	}
	// 添加服务权限信息
	accessControlModel := &dao.AccessControl{
		ServiceId:         serviceInfoModel.Id,
		OpenAuth:          param.OpenAuth,
		BlackList:         param.BlackList,
		WhiteList:         param.WhiteList,
		ClientIPFlowLimit: param.ClientipFlowLimit,
		ServiceFlowLimit:  param.ServiceFlowLimit,
	}
	if err := accessControlModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务权限信息报错：" + err.Error())
	}
	// 添加服务负载均衡信息
	loadBalanceModel := &dao.LoadBalance{
		ServiceId:              serviceInfoModel.Id,
		RoundType:              param.RoundType,
		IpList:                 param.IpList,
		WeightList:             param.WeightList,
		UpstreamConnectTimeout: param.UpstreamConnectTimeout,
		UpstreamHeaderTimeout:  param.UpstreamHeaderTimeout,
		UpstreamIdleTimeout:    param.UpstreamIdleTimeout,
		UpstreamMaxIdle:        param.UpstreamMaxIdle,
	}
	if err := loadBalanceModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务负载均衡信息报错：" + err.Error())
	}
	// 事务提交
	ss.tx.Commit()
	return nil
}

// GRPC 服务添加
func (ss *ServiceServices) AddServiceInfoGRPC(c *gin.Context, param *dto.ServiceAddGRPCInput) error {
	// 校验服务名称是否存在
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{ServiceName: param.ServiceName, IsDelete: 0})
	if err == nil {
		return errors.New(serviceInfo.ServiceName + "服务名称已经存在")
	}

	// 校验端口是否被TCP或者GRPC服务占用
	tcpRuleSearch := &dao.TcpRule{Port: param.Port}
	if _, err = tcpRuleSearch.Find(c, ss.tx, tcpRuleSearch); err != gorm.ErrRecordNotFound {
		return errors.New("服务端口已经被TCP服务占用")
	}
	grpcRuleSearch := &dao.GrpcRule{Port: param.Port}
	if _, err = grpcRuleSearch.Find(c, ss.tx, grpcRuleSearch); err != gorm.ErrRecordNotFound {
		return errors.New("服务端口已经被GRPC服务占用")
	}

	// 校验IP列表和权重列表是否相等
	if len(strings.Split(param.IpList, "\n")) !=
		len(strings.Split(param.WeightList, "\n")) {
		return errors.New("IP列表和权重列表不一致")
	}
	// 开启事务
	ss.tx = ss.tx.Begin()
	// 添加服务基本信息
	serviceInfoModel := &dao.ServiceInfo{
		LoadType:    public.LoadTypeGRPC,
		ServiceName: param.ServiceName,
		ServiceDesc: param.ServiceDesc,
		IsDelete:    0,
	}
	if err := serviceInfoModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务基本信息报错：" + err.Error())
	}
	// 添加GRPC规则信息
	grpcRuleMode := &dao.GrpcRule{
		ServiceId:      serviceInfoModel.Id,
		Port:           param.Port,
		HeaderTransfor: param.HeaderTransfor,
	}
	if err := grpcRuleMode.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务规则信息报错：" + err.Error())
	}
	// 添加服务权限信息
	accessControlModel := &dao.AccessControl{
		ServiceId:         serviceInfoModel.Id,
		OpenAuth:          param.OpenAuth,
		BlackList:         param.BlackList,
		WhiteList:         param.WhiteList,
		ClientIPFlowLimit: param.ClientipFlowLimit,
		ServiceFlowLimit:  param.ServiceFlowLimit,
		WhiteHostName:     param.WhiteHostName,
	}
	if err := accessControlModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务权限信息报错：" + err.Error())
	}
	// 添加服务负载均衡信息
	loadBalanceModel := &dao.LoadBalance{
		ServiceId:  serviceInfoModel.Id,
		RoundType:  param.RoundType,
		IpList:     param.IpList,
		WeightList: param.WeightList,
		ForbidList: param.ForbidList,
	}
	if err := loadBalanceModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务负载均衡信息报错：" + err.Error())
	}
	// 事务提交
	ss.tx.Commit()
	return nil
}

// TCP 服务添加
func (ss *ServiceServices) AddServiceInfoTCP(c *gin.Context, param *dto.ServiceAddTCPInput) error {
	// 校验服务名称是否存在
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{ServiceName: param.ServiceName, IsDelete: 0})
	if err == nil {
		return errors.New(serviceInfo.ServiceName + "服务名称已经存在")
	}

	// 校验端口是否被TCP或者GRPC服务占用
	tcpRuleSearch := &dao.TcpRule{Port: param.Port}
	if _, err = tcpRuleSearch.Find(c, ss.tx, tcpRuleSearch); err != gorm.ErrRecordNotFound {
		return errors.New("服务端口已经被TCP服务占用")
	}
	grpcRuleSearch := &dao.GrpcRule{Port: param.Port}
	if _, err = grpcRuleSearch.Find(c, ss.tx, grpcRuleSearch); err != gorm.ErrRecordNotFound {
		return errors.New("服务端口已经被GRPC服务占用")
	}

	// 校验IP列表和权重列表是否相等
	if len(strings.Split(param.IpList, "\n")) !=
		len(strings.Split(param.WeightList, "\n")) {
		return errors.New("IP列表和权重列表不一致")
	}
	// 开启事务
	ss.tx = ss.tx.Begin()
	// 添加服务基本信息
	serviceInfoModel := &dao.ServiceInfo{
		LoadType:    public.LoadTypeTCP,
		ServiceName: param.ServiceName,
		ServiceDesc: param.ServiceDesc,
		IsDelete:    0,
	}
	if err := serviceInfoModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务基本信息报错：" + err.Error())
	}
	// 添加TCP规则信息
	tcpRuleMode := &dao.TcpRule{
		ServiceId: serviceInfoModel.Id,
		Port:      param.Port,
	}
	if err := tcpRuleMode.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务规则信息报错：" + err.Error())
	}
	// 添加服务权限信息
	accessControlModel := &dao.AccessControl{
		ServiceId:         serviceInfoModel.Id,
		OpenAuth:          param.OpenAuth,
		BlackList:         param.BlackList,
		WhiteList:         param.WhiteList,
		ClientIPFlowLimit: param.ClientipFlowLimit,
		ServiceFlowLimit:  param.ServiceFlowLimit,
		WhiteHostName:     param.WhiteHostName,
	}
	if err := accessControlModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务权限信息报错：" + err.Error())
	}
	// 添加服务负载均衡信息
	loadBalanceModel := &dao.LoadBalance{
		ServiceId:  serviceInfoModel.Id,
		RoundType:  param.RoundType,
		IpList:     param.IpList,
		WeightList: param.WeightList,
		ForbidList: param.ForbidList,
	}
	if err := loadBalanceModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("添加服务负载均衡信息报错：" + err.Error())
	}
	// 事务提交
	ss.tx.Commit()
	return nil
}

// HTTP 服务修改逻辑
func (ss *ServiceServices) UpdateServiceInfoHTTP(c *gin.Context, param *dto.ServiceUpdateHTTPInput) error {
	// 校验IP列表和权重列表是否相等
	if len(strings.Split(param.IpList, "\n")) !=
		len(strings.Split(param.WeightList, "\n")) {
		return errors.New("IP列表和权重列表不一致")
	}
	// 获取服务基本信息
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{Id: param.Id})
	if serviceInfo == nil {
		return errors.New("服务不存在：" + err.Error())
	}
	// 获取服务关联的数据
	serviceDetailServicesModel, err := NewServiceDetailServices()
	if err != nil {
		return err
	}
	serviceDetail, err := serviceDetailServicesModel.GetServiceDetail(c, serviceInfo)
	if err != nil {
		return errors.New("查询服务关联信息失败：" + err.Error())
	}
	// 开启事务
	ss.tx = ss.tx.Begin()
	// 修改服务基本信息
	serviceInfoModel := serviceDetail.Info
	serviceInfoModel.ServiceDesc = param.ServiceDesc
	if err := serviceInfoModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务基本信息报错：" + err.Error())
	}
	// 修改HTTP规则信息
	httpRuleMode := serviceDetail.HTTPRule
	httpRuleMode.NeedHttps = param.NeedHttps
	httpRuleMode.NeedWebsocket = param.NeedWebsocket
	httpRuleMode.NeedStripUri = param.NeedStripUri
	httpRuleMode.UrlRewrite = param.UrlRewrite
	httpRuleMode.HeaderTransfor = param.HeaderTransfor
	if err := httpRuleMode.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务规则信息报错：" + err.Error())
	}
	// 修改服务权限信息
	accessControlModel := serviceDetail.AccessControl
	accessControlModel.OpenAuth = param.OpenAuth
	accessControlModel.BlackList = param.BlackList
	accessControlModel.WhiteList = param.WhiteList
	accessControlModel.ClientIPFlowLimit = param.ClientipFlowLimit
	accessControlModel.ServiceFlowLimit = param.ServiceFlowLimit
	if err := accessControlModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务权限信息报错：" + err.Error())
	}
	// 修改服务负载均衡信息
	loadBalanceModel := serviceDetail.LoadBalance
	loadBalanceModel.RoundType = param.RoundType
	loadBalanceModel.IpList = param.IpList
	loadBalanceModel.WeightList = param.WeightList
	loadBalanceModel.UpstreamConnectTimeout = param.UpstreamConnectTimeout
	loadBalanceModel.UpstreamHeaderTimeout = param.UpstreamHeaderTimeout
	loadBalanceModel.UpstreamIdleTimeout = param.UpstreamIdleTimeout
	loadBalanceModel.UpstreamMaxIdle = param.UpstreamMaxIdle
	if err := loadBalanceModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务负载均衡信息报错：" + err.Error())
	}
	// 事务提交
	ss.tx.Commit()
	return nil
}

// GRPC 服务修改逻辑
func (ss *ServiceServices) UpdateServiceInfoGRPC(c *gin.Context, param *dto.ServiceUpdateGRPCInput) error {
	// 校验IP列表和权重列表是否相等
	if len(strings.Split(param.IpList, "\n")) !=
		len(strings.Split(param.WeightList, "\n")) {
		return errors.New("IP列表和权重列表不一致")
	}
	// 获取服务基本信息
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{Id: param.Id})
	if serviceInfo == nil {
		return errors.New("服务不存在：" + err.Error())
	}
	// 获取服务关联的数据
	serviceDetailServicesModel, err := NewServiceDetailServices()
	if err != nil {
		return err
	}
	serviceDetail, err := serviceDetailServicesModel.GetServiceDetail(c, serviceInfo)
	if err != nil {
		return errors.New("查询服务关联信息失败：" + err.Error())
	}
	// 开启事务
	ss.tx = ss.tx.Begin()
	// 修改服务基本信息
	serviceInfoModel := serviceDetail.Info
	serviceInfoModel.ServiceDesc = param.ServiceDesc
	if err := serviceInfoModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务基本信息报错：" + err.Error())
	}
	// 修改GRPC规则信息
	grpcRuleMode := serviceDetail.GRPCRule
	grpcRuleMode.ServiceId = serviceInfoModel.Id
	grpcRuleMode.HeaderTransfor = param.HeaderTransfor
	if err := grpcRuleMode.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务规则信息报错：" + err.Error())
	}
	// 修改服务权限信息
	accessControlModel := serviceDetail.AccessControl
	accessControlModel.ServiceId = serviceInfoModel.Id
	accessControlModel.OpenAuth = param.OpenAuth
	accessControlModel.BlackList = param.BlackList
	accessControlModel.WhiteList = param.WhiteList
	accessControlModel.ClientIPFlowLimit = param.ClientipFlowLimit
	accessControlModel.ServiceFlowLimit = param.ServiceFlowLimit
	accessControlModel.WhiteHostName = param.WhiteHostName
	if err := accessControlModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务权限信息报错：" + err.Error())
	}
	// 修改服务负载均衡信息
	loadBalanceModel := serviceDetail.LoadBalance
	loadBalanceModel.ServiceId = serviceInfoModel.Id
	loadBalanceModel.RoundType = param.RoundType
	loadBalanceModel.IpList = param.IpList
	loadBalanceModel.WeightList = param.WeightList
	loadBalanceModel.ForbidList = param.ForbidList
	if err := loadBalanceModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务负载均衡信息报错：" + err.Error())
	}
	// 事务提交
	ss.tx.Commit()
	return nil
}

// TCP 服务修改逻辑
func (ss *ServiceServices) UpdateServiceInfoTCP(c *gin.Context, param *dto.ServiceUpdateTCPInput) error {
	// 校验IP列表和权重列表是否相等
	if len(strings.Split(param.IpList, "\n")) !=
		len(strings.Split(param.WeightList, "\n")) {
		return errors.New("IP列表和权重列表不一致")
	}
	// 获取服务基本信息
	serviceInfo, err := ss.Find(c, &dao.ServiceInfo{Id: param.Id})
	if serviceInfo == nil {
		return errors.New("服务不存在：" + err.Error())
	}
	// 获取服务关联的数据
	serviceDetailServicesModel, err := NewServiceDetailServices()
	if err != nil {
		return err
	}
	serviceDetail, err := serviceDetailServicesModel.GetServiceDetail(c, serviceInfo)
	if err != nil {
		return errors.New("查询服务关联信息失败：" + err.Error())
	}
	// 开启事务
	ss.tx = ss.tx.Begin()
	// 修改服务基本信息
	serviceInfoModel := serviceDetail.Info
	serviceInfoModel.ServiceDesc = param.ServiceDesc
	if err := serviceInfoModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务基本信息报错：" + err.Error())
	}
	// 修改TCP规则信息
	/*tcpRuleMode := serviceDetail.TCPRule
	tcpRuleMode.ServiceId = serviceInfoModel.Id
	if err := tcpRuleMode.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务规则信息报错：" + err.Error())
	}*/
	// 修改服务权限信息
	accessControlModel := serviceDetail.AccessControl
	accessControlModel.ServiceId = serviceInfoModel.Id
	accessControlModel.OpenAuth = param.OpenAuth
	accessControlModel.BlackList = param.BlackList
	accessControlModel.WhiteList = param.WhiteList
	accessControlModel.ClientIPFlowLimit = param.ClientipFlowLimit
	accessControlModel.ServiceFlowLimit = param.ServiceFlowLimit
	accessControlModel.WhiteHostName = param.WhiteHostName
	if err := accessControlModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务权限信息报错：" + err.Error())
	}
	// 修改服务负载均衡信息
	loadBalanceModel := serviceDetail.LoadBalance
	loadBalanceModel.ServiceId = serviceInfoModel.Id
	loadBalanceModel.RoundType = param.RoundType
	loadBalanceModel.IpList = param.IpList
	loadBalanceModel.WeightList = param.WeightList
	loadBalanceModel.ForbidList = param.ForbidList
	if err := loadBalanceModel.Save(c, ss.tx); err != nil {
		// 事务回滚
		ss.tx.Rollback()
		return errors.New("修改服务负载均衡信息报错：" + err.Error())
	}
	// 事务提交
	ss.tx.Commit()
	return nil
}
